package per.wsj.okhttp

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_main.*
import per.wsj.commonlib.utils.LogUtil
import per.wsj.httplib.ok.LoadState

class MainActivity : AppCompatActivity() {

    private val viewModel: MainViewModel by lazy { ViewModelProvider(this).get(MainViewModel::class.java) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnRequest1.setOnClickListener {
            viewModel.getChapters1()
        }

        tvRequest2.setOnClickListener {
            viewModel.getChapters2()
        }

        tvRequest3.setOnClickListener {
//            viewModel.getChapters3()
            viewModel.getGitStarUser()
        }

        var counter = 0

        viewModel.test.observe(this) {
            LogUtil.e("receive: $it " + ++counter)
        }

        viewModel.loadState.observe(this) {
            changeLoadState(it)
        }

        viewModel.chapters.observe(this) {
            it.forEach { item ->
                LogUtil.e(item.toString())
            }
        }

//        startActivity<Main2Activity>("key1" to "value1", "key2" to "value2")

        TestUtils.request<List<String>>("123")
//        TestUtils.request2<List<String>>("123")

    }

    /**
     * 主线程中先执行完当前方法，再执行post的runnable
     * 异步线程中post的runnable可能优先执行
     */
    fun test() {
        LogUtil.e("aaa")
        Handler(Looper.getMainLooper()).post {
            LogUtil.e("wsj----------------")
        }
        for (i in 0..3000) {
            LogUtil.e("bbb $i")
        }
    }

    inline fun <reified T> showData(msg: String) {
        val type = object : TypeToken<T>() {}.type
        LogUtil.e(type.typeName)
        LogUtil.e("aaaaaaaa$msg")
    }

    private fun changeLoadState(loadState: LoadState) {
        when (loadState) {
            is LoadState.Start -> {
                LogUtil.e("开始")
            }
            is LoadState.Error -> {
                LogUtil.e("异常：${loadState.msg}")
            }
            is LoadState.Finish -> {
                LogUtil.e("完成")
            }
        }
    }
}